package com.chwn.curiousdiary.ui.main.presenter;

import android.text.TextUtils;

import com.chwn.curiousdiary.DiaryApplication;
import com.chwn.curiousdiary.api.ISystemApi;
import com.chwn.curiousdiary.api.NetWork;
import com.chwn.curiousdiary.bean.MineNumBean;
import com.chwn.curiousdiary.gloable.Constant;
import com.chwn.curiousdiary.gloable.CustomEvent;
import com.chwn.curiousdiary.ui.main.contract.MineContract;
import com.chwn.harulib.mvp.rx.HttpResult;
import com.chwn.harulib.mvp.rx.RxSchedulers;

import java.util.List;

import de.greenrobot.event.EventBus;
import rx.Observer;

/**
 * Created by Myshikin on 2017/3/20.
 */

public class MinePresenter extends MineContract.Presenter {

    /**
     * 收藏与未读消息数量
     */
    private Observer<HttpResult<List<MineNumBean>>> mineObserver = new Observer<HttpResult<List<MineNumBean>>>() {
        @Override
        public void onCompleted() {
            mView.onRequestSuccess();
        }

        @Override
        public void onError(Throwable e) {
            mView.onRequestError(e);
        }

        @Override
        public void onNext(HttpResult<List<MineNumBean>> httpResult) {
            if (httpResult.getResult() == 1) {
                mView.showMyInfo(httpResult.getResdata().get(0));
                DiaryApplication.mInstance.updateCoinCount(httpResult.getResdata().get(0).getCuriosityCount());
                EventBus.getDefault().post(new CustomEvent(CustomEvent.UPDATE_USER_INFO));
            }
        }
    };

    @Override
    public void getMyInfo() {
        String userToken = DiaryApplication.mInstance.getUserToken();
        if (TextUtils.isEmpty(userToken)) {
            return;
        }
        NetWork.getInstance()
                .getApiService(ISystemApi.class)
                .collectAndUnReadNum(Constant.OSTYPE, userToken)
                .compose(RxSchedulers.<HttpResult<List<MineNumBean>>>io_main())
                .subscribe(mineObserver);

    }
}
